package field

import "gitee.com/yanwc/net/utils"

type (
	CRC   U2 
	CRCRaw U2Raw
)

func (crc CRC) Raw() (out CRCRaw) {
	copy(out[:], utils.NumberToBytesWithBigEndian(crc))
	return
}

func (crc CRCRaw) Type() CRC {
	return utils.BytesToNumber[CRC](crc[:])
}

func (crc CRCRaw) Slice() []byte {
	return crc[:]
}

// CRC循环校验
func (crc CRCRaw) Check(data []byte) bool {
	return crc.Type() == NewCRC(data)
}

func NewCRC(data []byte) CRC {
	ck_a := 0
	ck_b := 0
	for _, i := range data {
		ck_a = ck_a + int(i)
		ck_b = ck_b + ck_a
	}

	return CRC(ck_a & ck_b)
}

func WithCRC(data []byte) []byte {
	data = append(data, NewCRC(data).Raw().Slice()...)
	return data
}
